<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>视频语音通话: {{ room.name }}</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.1.3/css/bootstrap.min.css" rel="stylesheet">
    <link rel="preconnect" href="https://cdn.bootcdn.net">
    <link href="https://vjs.zencdn.net/7.19.2/video-js.css" rel="stylesheet" />
    <style>
        body {
            background: #1a1a1a;
            color: white;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        .video-container {
            position: relative;
            width: 100%;
            height: 80vh;
            background: #000;
            border-radius: 10px;
            overflow: hidden;
            margin-bottom: 20px;
        }
        .video-element {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        .local-video {
            position: absolute;
            bottom: 20px;
            right: 20px;
            width: 300px;
            height: 225px;
            border: 3px solid #007bff;
            border-radius: 10px;
            background: #000;
            z-index: 10;
        }
        .audio-only .local-video {
            display: none !important;
        }
        .control-bar {
            position: fixed;
            bottom: 20px;
            left: 50%;
            transform: translateX(-50%);
            background: rgba(0, 0, 0, 0.8);
            padding: 15px 30px;
            border-radius: 50px;
            backdrop-filter: blur(10px);
        }
        .control-btn {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            border: none;
            margin: 0 10px;
            font-size: 20px;
            transition: all 0.3s ease;
        }
        .control-btn:hover {
            transform: scale(1.1);
        }
        .btn-mute {
            background: #6c757d;
            color: white;
        }
        .btn-mute.muted {
            background: #dc3545;
        }
        .btn-video {
            background: #6c757d;
            color: white;
        }
        .btn-video.off {
            background: #dc3545;
        }
        .btn-end {
            background: #dc3545;
            color: white;
        }
        .status-info {
            position: absolute;
            top: 20px;
            left: 20px;
            background: rgba(0, 0, 0, 0.7);
            padding: 10px 20px;
            border-radius: 20px;
            font-size: 14px;
        }
        .remote-placeholder {
            display: flex;
            align-items: center;
            justify-content: center;
            height: 100%;
            font-size: 18px;
            color: #666;
        }
        .audio-placeholder {
            text-align: center;
            padding: 40px;
        }
        .audio-avatar {
            width: 120px;
            height: 120px;
            border-radius: 50%;
            background: linear-gradient(45deg, #667eea, #764ba2);
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 48px;
            margin: 0 auto 20px;
        }

        .video-container {
           background: #000;
        }

        /* 确保视频填充容器 */
        #remote-video, #local-video {
            margin: 0;
            padding: 0;
        }

        body, html {
            margin: 0;
            padding: 0;
            height: 100vh;
            overflow: hidden;
        }

        /* 视频区域占据剩余空间 */
        .flex-grow-1 {
            flex: 1 1 auto;
        }

        /* 控制栏固定高度 */
        .control-area {
            flex: 0 0 auto;
            min-height: 80px;
        }

        .recordings-panel {
            position: fixed;
            top: 0;
            right: -400px;
            width: 380px;
            height: 100vh;
            background: rgba(26, 26, 26, 0.95);
            backdrop-filter: blur(10px);
            border-left: 1px solid #333;
            z-index: 1000;
            transition: right 0.3s ease;
            display: flex;
            flex-direction: column;
        }

        .recordings-panel.show {
            right: 0;
        }

        .recordings-header {
            padding: 20px;
            border-bottom: 1px solid #333;
            display: flex;
            justify-content: space-between;
            align-items: center;
            background: rgba(0, 0, 0, 0.8);
        }

        .recordings-content {
            flex: 1;
            overflow-y: auto;
            padding: 10px;
        }

        .recordings-list {
            display: flex;
            flex-direction: column;
            gap: 10px;
        }

        .recording-item {
            background: rgba(255, 255, 255, 0.1);
            border-radius: 8px;
            padding: 15px;
            border: 1px solid #333;
            transition: all 0.3s ease;
        }

        .recording-item:hover {
            background: rgba(255, 255, 255, 0.15);
            border-color: #007bff;
        }

        .recording-info {
            margin-bottom: 10px;
        }

        .recording-name {
            font-weight: bold;
            margin-bottom: 5px;
        }

        .recording-meta {
            font-size: 12px;
            color: #aaa;
        }

        .recording-actions {
            display: flex;
            gap: 8px;
        }

        .recording-actions .btn {
            flex: 1;
            font-size: 12px;
            padding: 5px 10px;
        }

        /* Video.js 自定义样式 */
        .video-js {
            width: 100%;
            border-radius: 8px;
        }
        .video-js .vjs-big-play-button {
            top: 50%;
            left: 50%;
            margin-top: -0.81666em;
            margin-left: -1.5em;
        }
        .video-js .vjs-control-bar {
            background: rgba(0, 0, 0, 0.7);
        }

        /* 录制列表面板样式 */
        .recordings-panel {
            position: fixed;
            top: 0;
            right: -400px;
            width: 380px;
            height: 100vh;
            background: rgba(26, 26, 26, 0.95);
            backdrop-filter: blur(10px);
            border-left: 1px solid #333;
            z-index: 1000;
            transition: right 0.3s ease;
            display: flex;
            flex-direction: column;
        }

        .recordings-panel.show {
            right: 0;
        }

        .recordings-header {
            padding: 20px;
            border-bottom: 1px solid #333;
            display: flex;
            justify-content: space-between;
            align-items: center;
            background: rgba(0, 0, 0, 0.8);
        }

        .recordings-content {
            flex: 1;
            overflow-y: auto;
            padding: 10px;
        }

        .recordings-list {
            display: flex;
            flex-direction: column;
            gap: 10px;
        }

        .recording-item {
            background: rgba(255, 255, 255, 0.1);
            border-radius: 8px;
            padding: 15px;
            border: 1px solid #333;
            transition: all 0.3s ease;
        }

        .recording-item:hover {
            background: rgba(255, 255, 255, 0.15);
            border-color: #007bff;
        }

        .recording-info {
            margin-bottom: 10px;
        }

        .recording-name {
            font-weight: bold;
            margin-bottom: 5px;
        }

        .recording-meta {
            font-size: 12px;
            color: #aaa;
        }

        .recording-actions {
            display: flex;
            gap: 8px;
        }

        .recording-actions .btn {
            flex: 1;
            font-size: 12px;
            padding: 5px 10px;
        }

        /* 视频播放器模态框样式 */
        .video-player-modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.95);
            z-index: 10000;
            display: flex;
            justify-content: center;
            align-items: center;
            backdrop-filter: blur(5px);
        }

        .video-player-container {
            position: relative;
            width: 90%;
            max-width: 1200px;
            background: #2d2d2d;
            border-radius: 12px;
            padding: 0;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5);
            border: 1px solid #444;
        }

        .video-player-header {
            padding: 15px 20px;
            border-bottom: 1px solid #444;
            display: flex;
            justify-content: space-between;
            align-items: center;
            background: #363636;
            border-radius: 12px 12px 0 0;
        }

        .video-player-content {
            padding: 20px;
        }

        .video-player-footer {
            padding: 15px 20px;
            border-top: 1px solid #444;
            display: flex;
            gap: 10px;
            justify-content: flex-end;
            background: #363636;
            border-radius: 0 0 12px 12px;
        }
    </style>
</head>
<body>
    <!-- 精确比例控制 -->
    <div class="container-fluid d-flex flex-column" style="height: 100vh;">
        <div style="height: 10vh;"></div>
        <!-- 房间信息区域 -->
        <div style="height: 10vh;">
            <span>房间名称: {{ room.name }}</span>
            <span class="room_no">房间号: {{ room.code }}</span>
            <span class="user_name">用户: {{ room.user_id }}</span>
        </div>
        <!-- 视频区域 - 85% 高度 -->
        <div style="height: 65vh;">
            <div class="video-container h-100">
                <div class="row h-100 g-0 m-0">
                    <!-- 主视频 60% 宽度 -->
                    <div class="col-7 h-100 p-0 bg-black position-relative">
                        <div id="remote-placeholder" class="h-100 w-100 d-flex justify-content-center align-items-center text-white">
                            <div class="text-center">
                                <div style="font-size: 96px; margin-bottom: 30px;">🎥</div>
                                <h3>等待对方加入...</h3>
                            </div>
                        </div>
                        <video id="remote-video" class="h-100 w-100" autoplay playsinline style="display: none; object-fit: cover;"></video>
                    </div>

                    <!-- 本地视频 40% 宽度 -->
                    <div class="col-5 h-100 p-2">
                        <div class="h-100 w-100 bg-dark rounded overflow-hidden border border-primary">
                            <video id="local-video" class="h-100 w-100" autoplay playsinline muted style="object-fit: cover;"></video>
                            <div class="position-absolute bottom-0 start-0 w-100 p-1 text-white bg-dark bg-opacity-75 text-center">
<!--                                <small>我的视频</small>-->
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 控制栏区域 - 15% 高度 -->
        <div style="height: 15vh;" class="bg-dark d-flex align-items-center justify-content-center border-top border-secondary">
            <div class="text-center w-100">
                <!-- 控制按钮区域 -->
                <div class="btn-group" role="group">
                    <button id="leave-call" class="btn btn-danger btn-lg mx-2">
                        <i class="fas fa-phone-slash"></i> 结束通话
                    </button>
                    <button id="recording" class="btn btn-danger btn-lg mx-2">
                        <i class="fas fa-record-vinyl"></i> 开始录制
                    </button>
                    <button id="show-recordings" class="btn btn-outline-info btn-lg mx-2">
                        <i class="fas fa-list"></i> 录制列表
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- 录制列表面板 - 放在这里 -->
    <div id="recordings-panel" class="recordings-panel">
        <div class="recordings-header">
            <h5>录制文件列表</h5>
            <button id="close-recordings" class="btn btn-sm btn-outline-secondary">×</button>
        </div>
        <div class="recordings-content">
            <div id="recordings-list" class="recordings-list">
                <!-- 动态加载的录制文件列表 -->
            </div>
        </div>
    </div>

    <!-- Video.js 播放器模态框 -->
    <div id="video-player-modal" class="video-player-modal" style="display: none;">
        <div class="video-player-container">
            <div class="video-player-header">
                <div style="color: #fff; font-weight: 500;" id="video-player-title">播放录制文件</div>
                <button onclick="closeVideoPlayer()" style="
                    background: #dc3545;
                    color: white;
                    border: none;
                    border-radius: 50%;
                    width: 32px;
                    height: 32px;
                    cursor: pointer;
                    font-size: 18px;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    transition: background 0.3s;
                " onmouseover="this.style.background='#c82333'" onmouseout="this.style.background='#dc3545'">×</button>
            </div>

            <div class="video-player-content">
                <video
                    id="recording-video-player"
                    class="video-js vjs-default-skin"
                    controls
                    preload="auto"
                    width="100%"
                    height="450"
                    data-setup="{}"
                >
                    <p class="vjs-no-js">
                        要观看此视频，请启用JavaScript，并考虑升级到支持
                        <a href="https://videojs.com/html5-video-support/" target="_blank">HTML5视频的Web浏览器</a>
                    </p>
                </video>
            </div>

            <div class="video-player-footer">
                <button onclick="downloadCurrentVideo()" class="btn btn-success btn-sm">
                    <i class="fas fa-download"></i> 下载视频
                </button>
                <button onclick="closeVideoPlayer()" class="btn btn-secondary btn-sm">关闭</button>
            </div>
        </div>
    </div>

    <script src="http://localhost:8000/static/ZegoExpressWebRTC-3.11.0.js"></script>
<!--    &lt;!&ndash; Video.js JS &ndash;&gt;-->
<!--    <script src="https://vjs.zencdn.net/7.19.2/video.min.js"></script>-->
    <!-- Video.js 使用更快的 CDN -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/video.js/7.19.2/video-js.min.css" rel="stylesheet">
    <!-- Font Awesome -->
<!--    <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/js/all.min.js"></script>-->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/js/all.min.js" defer></script>

    <script>

        const appId = 1398629913;

        const room = getRoomFromURL();
        const userId = room.user_id;
        const roomCode = room.code;
        let isRecording = false;
        let recordingId;
        const isCreator = (userId == room.user_a); // 是否创建房间人员

        let token = null;
        let zg;
        let localStream;

        let recordingsPanel = document.getElementById('recordings-panel');
        let showRecordingsBtn = document.getElementById('show-recordings');
        let closeRecordingsBtn = document.getElementById('close-recordings');
        let recordingsList = document.getElementById('recordings-list');

        let currentVideoUrl = '';
        let currentVideoFilename = '';
        let videoPlayer = null;

        // 从URL参数中获取room信息
        function getRoomFromURL() {
            const urlParams = new URLSearchParams(window.location.search);
            return {
                code: urlParams.get('code'),
                name: urlParams.get('name'),
                user_id: urlParams.get('user_id'),
                user_a: urlParams.get('user_a')
            };
        }

        async function generateToken() {
            const params = new URLSearchParams({
                room_code: roomCode,
                user_id: userId
            }).toString();
            const response = await fetch(`http://localhost:8000/api/v1/token?${params}`, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                }
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const data = await response.json();
            token = data.data.token; // 正确赋值给外部变量
            console.log('==========token: ' + token);
            return token;
        }

        // 展示本地视频
        async function localDisplay() {
            try {
                const stream = await navigator.mediaDevices.getUserMedia({
                    video: true,
                    audio: true
                });
                const video = document.getElementById("local-video");
                video.srcObject = stream;
                console.log("==========摄像头测试成功");
            } catch (error) {
                console.error("==========摄像头访问失败:", error);
            }
        }

        // 初始化ZEGO引擎
        function initEngine() {
            zg = new ZegoExpressEngine(appId, ""); // 使用正确的变量名appId

            initEventHandlers();
            console.log("==========ZEGO引擎初始化成功");
        }

        // 注册事件处理器
        function initEventHandlers() {
            zg.on('roomStateChanged', (roomId, state, errorCode, extendData) => {
                console.log(`==========房间状态变化: ${state}, 错误码: ${errorCode}`);

                if (state === 'LOGINED') {
                    console.log("==========登录房间成功，可以开始推流");
                    startPublishing();
                } else if (state === 'DISCONNECTED') {
                    console.error("==========登录房间失败");
                }
            });

            zg.on('publisherStateUpdate', (result) => {
                console.log(`推流状态: ${result.state}, 流ID: ${result.streamID}`);

                if (result.state === 'PUBLISHING') {
                    console.log("==========推流成功");
                    document.getElementById('stop-btn').disabled = false;
                } else if (result.state === 'NO_PUBLISH') {
                    console.error("==========推流失败");
                }
            });

            zg.on('roomTokenWillExpire', (roomId, remainTimeInSecond) => {
                console.log(`Token将在${remainTimeInSecond}秒后过期，需要更新Token`);
            });

            // 监听远程流更新
            zg.on('roomStreamUpdate', async (roomID, updateType, streamList) => {
                console.log(`==========房间流更新: ${updateType}`, streamList);

                if (updateType === 'ADD') {
                    // 有新流加入，开始拉流
                    for (const stream of streamList) {
                        if (stream.user.userID !== userId) { // 排除自己的流
                            await playRemoteStream(stream);
                        }
                    }
                } else if (updateType === 'DELETE') {
                    // 有流离开，停止拉流
                    for (const stream of streamList) {
                        if (stream.user.userID !== userId) {
                            stopRemoteStream(stream);
                        }
                    }
                }
            });
        }

        // 登录房间
        async function loginRoom() {
            try {
                const result = await zg.loginRoom(roomCode, token, { // 使用roomCode作为房间ID
                    userID: userId,
                    userName: userId
                });

                if (result) {
                    console.log("==========房间登录成功");
                }
            } catch (error) {
                console.error("==========房间登录失败:", error);
            }
        }

        // 创建本地音视频流并开始推流
        async function startPublishing() {
            try {
                // 使用正确的API创建流
                localStream = await zg.createStream({
                    camera: {
                        video: true,
                        audio: true
                    }
                });

                // 将流绑定到video元素（如果还没有显示的话）
                const localVideo = document.getElementById("local-video");
                if (!localVideo.srcObject) {
                    localVideo.srcObject = localStream;
                }

                // 生成流ID
                const streamID = "stream_" + userId + "_" + Date.now();

                // 开始推流
                await zg.startPublishingStream(streamID, localStream);

                console.log(`==========开始推流，流ID: ${streamID}`);
            } catch (error) {
                console.error("==========创建流或推流失败:", error);
            }
        }

        // 页面加载完成后初始化
        window.onload = async function() { // 改为async函数
            try {
                if (!isCreator) {
                    // 加入者隐藏录制按钮
                    document.getElementById('recording').style.display = 'none';
                }
                // 1. 生成token
                await generateToken();

                // 2. 初始化引擎
                initEngine();

                // 3. 展示本地视频
                await localDisplay();

                // 4. 登录房间进行推流
                await loginRoom();

            } catch (error) {
                console.error("==========初始化失败:", error);
            }
        };

        async function cleanupResources() {
            if (!zg) {
                console.log("==========引擎不存在，无需清理");
                return;
            }

            try {
                console.log("==========开始清理资源");

                // 停止推流
                await zg.stopPublishingStream();
                console.log("==========推流已停止");

                // 销毁本地流
                if (localStream) {
                    await zg.destroyStream(localStream);
                    localStream = null;
                    console.log("==========本地流已销毁");
                }

                // 登出房间
                await zg.logoutRoom(roomCode);
                console.log("==========已登出房间");

            } catch (error) {
                console.error("==========资源清理失败:", error);
            }
        }

        // 播放远程视频流
        async function playRemoteStream(streamInfo) {
            try {
                console.log("==========开始播放远程视频:", streamInfo);

                // 开始拉流
                const remoteStream = await zg.startPlayingStream(streamInfo.streamID);
                console.log("==========拉流成功，获取到媒体流:", remoteStream);

                // 获取视频区域和占位符
                const videoArea = document.querySelector('.col-7');
                const remotePlaceholder = document.getElementById('remote-placeholder');

                // 完全清空区域并创建全新视频元素
                videoArea.innerHTML = '';

                // 创建全新的视频元素
                const newVideo = document.createElement('video');
                newVideo.id = 'remote-video';
                newVideo.className = 'h-100 w-100';
                newVideo.autoplay = true;
                newVideo.playsinline = true;
                newVideo.style.cssText = 'object-fit: cover; display: block !important;';
                newVideo.srcObject = remoteStream;

                // 隐藏占位符
                videoArea.appendChild(newVideo);
                remotePlaceholder.style.display = 'none';
                console.log("==========全新视频元素创建完成");

            } catch (error) {
                console.error('==========播放远程视频失败:', error);
            }
        }

        // 停止远程流
        function stopRemoteStream(streamInfo) {
            try {
                // 停止拉流
                zg.stopPlayingStream(streamInfo.streamID);

                // 隐藏视频，显示占位符
                const remoteVideo = document.getElementById('remote-video');
                const remotePlaceholder = document.getElementById('remote-placeholder');

                remoteVideo.style.display = 'none';
                remotePlaceholder.style.display = 'flex';
                remoteVideo.srcObject = null;

                console.log(`==========停止播放远程视频: ${streamInfo.streamID}`);
            } catch (error) {
                console.error('==========停止远程视频失败:', error);
            }
        }

        // 录制按钮事件
        document.getElementById('recording').addEventListener('click', async function() {
            const recordingBtn = this;

            if (!isRecording) {
                // 开始录制
                try {
                    // 调用你的录制接口
                    const response = await fetch(`http://localhost:8000/api/v1/rooms/${roomCode}/record/start`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        }
                    });

                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }
                    const data = await response.json();
                    console.log('==========')

                    if (data.code == 0) {
                        isRecording = true;
                        recordingId = data.data.recording_id
                        console.log('==========' + recordingId)
                        recordingBtn.innerHTML = '<i class="fas fa-stop"></i> 停止录制';
                        recordingBtn.classList.remove('btn-outline-warning');
                        recordingBtn.classList.add('btn-warning');
                        console.log("==========开始录制成功");
                    } else {
                        throw new Error('录制启动失败');
                    }
                } catch (error) {
                    console.error("==========开始录制失败:", error);
                    alert('开始录制失败');
                }
            } else {
                // 停止录制
                try {
                    const response = await fetch(`http://localhost:8000/api/v1/rooms/${roomCode}/record/stop`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        }
                    });

                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }
                    const data = await response.json();

                    if (data.code == 0) {
                        isRecording = false;
                        recordingBtn.innerHTML = '<i class="fas fa-record-vinyl"></i> 开始录制';
                        recordingBtn.classList.remove('btn-warning');
                        recordingBtn.classList.add('btn-outline-warning');
                        console.log("==========停止录制成功");
                    } else {
                        throw new Error('录制停止失败');
                    }
                } catch (error) {
                    console.error("==========停止录制失败:", error);
                    alert('停止录制失败');
                }
            }
        });

        // 加载录制文件列表
        async function loadRecordingsList() {
            try {
                recordingsList.innerHTML = '<div class="text-center py-4">加载中...</div>';

                const response = await fetch(`http://localhost:8000/api/v1/recordings/${roomCode}`, {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json',
                    }
                });

                if (!response.ok) {
                    throw new Error('获取录制列表失败');
                }

                const data = await response.json();
                displayRecordings(data.data.files);

            } catch (error) {
                console.error('加载录制列表失败:', error);
                recordingsList.innerHTML = '<div class="text-center py-4 text-danger">加载失败</div>';
            }
        }

        // 显示/隐藏录制列表
        showRecordingsBtn.addEventListener('click', function() {
            recordingsPanel.classList.add('show');
            loadRecordingsList();
        });

        closeRecordingsBtn.addEventListener('click', function() {
            recordingsPanel.classList.remove('show');
        });

        // 播放录制文件 - 使用Video.js
        function playRecording(playUrl, filename) {
            console.log("播放录制文件:", filename, playUrl);

            // 先关闭可能存在的播放器
            closeVideoPlayer();

            currentVideoUrl = playUrl;
            currentVideoFilename = filename;

            // 显示模态框
            const modal = document.getElementById('video-player-modal');
            const title = document.getElementById('video-player-title');

            title.textContent = `播放录制文件: ${filename}`;
            modal.style.display = 'flex';

            // 直接使用原生video标签，跳过Video.js
            const videoContainer = document.querySelector('.video-player-content');
            videoContainer.innerHTML = `
                <video
                    id="native-video-player"
                    controls
                    autoplay
                    style="width: 100%; max-height: 70vh; border-radius: 8px; background: #000;"
                >
                    <source src="${playUrl}" type="video/mp4">
                    您的浏览器不支持视频播放
                </video>
            `;

            const video = document.getElementById('native-video-player');
            video.onerror = function() {
                console.log('视频加载失败，显示下载选项');
                videoContainer.innerHTML = `
                    <div style="text-align: center; padding: 40px; color: white;">
                        <div style="font-size: 48px; margin-bottom: 20px;">❌</div>
                        <div>视频加载失败</div>
                        <button onclick="downloadCurrentVideo()" class="btn btn-primary mt-3">
                            <i class="fas fa-download"></i> 下载视频
                        </button>
                    </div>
                `;
            };

<!--            // 初始化Video.js播放器-->
<!--            initializeVideoPlayer(playUrl);-->

            // 添加键盘事件监听
            document.addEventListener('keydown', handleVideoPlayerKeydown);
        }

        // 下载当前视频
        function downloadCurrentVideo() {
            if (!currentVideoUrl) {
                alert('下载链接无效');
                return;
            }

            const link = document.createElement('a');
            link.href = currentVideoUrl;
            link.download = currentVideoFilename;
            link.style.display = 'none';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }

        // 初始化Video.js播放器
        function initializeVideoPlayer(videoUrl) {
            console.log("初始化Video.js播放器，URL:", videoUrl);

            // 如果播放器已存在，先完全销毁
            if (videoPlayer) {
                console.log("销毁现有播放器");
                videoPlayer.pause();
                videoPlayer.dispose();
                videoPlayer = null;

                // 重新创建video元素
                const videoContainer = document.querySelector('.video-player-content');
                const oldVideo = document.getElementById('recording-video-player');
                if (oldVideo) {
                    oldVideo.remove();
                }

                const newVideo = document.createElement('video');
                newVideo.id = 'recording-video-player';
                newVideo.className = 'video-js vjs-default-skin';
                newVideo.controls = true;
                newVideo.preload = 'auto';
                newVideo.width = '100%';
                newVideo.height = '450';
                newVideo.setAttribute('data-setup', '{}');

                newVideo.innerHTML = `
                    <p class="vjs-no-js">
                        要观看此视频，请启用JavaScript，并考虑升级到支持
                        <a href="https://videojs.com/html5-video-support/" target="_blank">HTML5视频的Web浏览器</a>
                    </p>
                `;

                videoContainer.appendChild(newVideo);
            }

            // 使用setTimeout确保DOM更新后再初始化
            setTimeout(() => {
                try {
                    // 初始化新的播放器
                    videoPlayer = videojs('recording-video-player', {
                        controls: true,
                        autoplay: true,
                        preload: 'auto',
                        fluid: true,
                        playbackRates: [0.5, 1, 1.25, 1.5, 2],
                        responsive: true,
                        html5: {
                            vhs: {
                                overrideNative: true
                            }
                        }
                    });

                    // 设置视频源
                    videoPlayer.src({
                        src: videoUrl,
                        type: 'video/mp4'
                    });

                    // 错误处理
                    videoPlayer.on('error', function() {
                        console.error('视频播放错误:', videoPlayer.error());
                        alert('视频加载失败，请检查网络连接或文件是否有效');
                    });

                    // 加载完成
                    videoPlayer.on('loadeddata', function() {
                        console.log('视频加载完成');
                    });

                    // 播放结束事件
                    videoPlayer.on('ended', function() {
                        console.log('视频播放结束');
                    });

                } catch (error) {
                    console.error('Video.js初始化失败:', error);
                    // 降级方案：使用原生video标签
                    fallbackToNativeVideo(videoUrl);
                }
            }, 100);
        }

        // 降级方案：使用原生video标签
        function fallbackToNativeVideo(videoUrl) {
            console.log("使用原生video标签降级方案");

            const videoContainer = document.querySelector('.video-player-content');
            videoContainer.innerHTML = `
                <video
                    id="native-video-player"
                    controls
                    autoplay
                    style="width: 100%; max-height: 70vh; border-radius: 8px; background: #000;"
                >
                    <source src="${videoUrl}" type="video/mp4">
                    您的浏览器不支持视频播放
                </video>
            `;

            const nativePlayer = document.getElementById('native-video-player');
            nativePlayer.onerror = function() {
                console.error('原生视频播放失败');
                alert('视频加载失败，请尝试下载后观看');
            };
        }

        // 键盘控制
        function handleVideoPlayerKeydown(event) {
            if (event.key === 'Escape') {
                closeVideoPlayer();
            }

            // 空格键播放/暂停
            if (event.key === ' ' && videoPlayer) {
                event.preventDefault();
                if (videoPlayer.paused()) {
                    videoPlayer.play();
                } else {
                    videoPlayer.pause();
                }
            }
        }

        // 关闭视频播放器
        function closeVideoPlayer() {
            console.log("关闭视频播放器");

            const modal = document.getElementById('video-player-modal');
            if (modal) {
                modal.style.display = 'none';
            }

            // 停止并销毁Video.js播放器
            if (videoPlayer) {
                try {
                    videoPlayer.pause();
                    videoPlayer.dispose();
                    videoPlayer = null;
                } catch (error) {
                    console.error('销毁播放器时出错:', error);
                }
            }

            // 清理原生video标签
            const nativePlayer = document.getElementById('native-video-player');
            if (nativePlayer) {
                nativePlayer.pause();
                nativePlayer.src = '';
                nativePlayer.remove();
            }

            // 移除事件监听
            document.removeEventListener('keydown', handleVideoPlayerKeydown);

            currentVideoUrl = '';
            currentVideoFilename = '';
        }

        // 在displayRecordings函数中更新播放按钮
        function displayRecordings(recordings) {
            if (!recordings || recordings.length === 0) {
                recordingsList.innerHTML = `
                    <div class="text-center py-4 text-muted">
                        <i class="fas fa-folder-open fa-2x mb-2"></i>
                        <div>暂无录制文件</div>
                    </div>
                `;
                return;
            }

            recordingsList.innerHTML = recordings.map(recording => `
                <div class="recording-item">
                    <div class="recording-info">
                        <div class="recording-name">${recording.filename || '录制文件'}</div>
                        <div class="recording-meta">
                            <div>名称: ${recording.name}</div>
                            <div>时间: ${recording.last_time}</div>
                            <div>链接: ${recording.url}</div>
                        </div>
                    </div>
                    <div class="recording-actions">
                        <button class="btn btn-sm btn-outline-primary"
                                onclick="playRecording('${recording.url}', '${recording.name}')">
                            <i class="fas fa-play"></i> 播放
                        </button>
                        <button class="btn btn-sm btn-outline-success"
                                onclick="downloadRecording('${recording.url}', '${recording.name}')">
                            <i class="fas fa-download"></i> 下载
                        </button>
                    </div>
                </div>
            `).join('');
        }

        // 独立的下载函数
        function downloadRecording(downloadUrl, filename) {
            if (!downloadUrl) {
                alert('下载链接无效');
                return;
            }

            const link = document.createElement('a');
            link.href = downloadUrl;
            link.download = filename;
            link.style.display = 'none';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }

        // 页面卸载前清理资源
        window.onbeforeunload = function() {
            cleanupResources().catch(e => {});
        };

        // 手动结束通话按钮
        document.getElementById('leave-call').addEventListener('click', async function() {
            await cleanupResources();

            // 跳转回首页
            setTimeout(() => {
                window.location.href = '/'; // 跳转到首页
            }, 1000); // 1秒后跳转
        });

    </script>
</body>